{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a04b7240",
   "metadata": {},
   "source": [
    "# Prerequisites\n",
    "\n",
    "These steps must be completed before running this notebook. Follow the instructions below to ensure your environment is properly set up and ready to execute the workflow.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "953bf765",
   "metadata": {},
   "source": [
    "## Step 1: Install Docker (Skip this is you have Docker Running)\n",
    "\n",
    "Docker is required to run Oracle in a containerized environment. Install Docker for your platform:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8657eae5",
   "metadata": {},
   "source": [
    "**macOS:**\n",
    "1. Download Docker Desktop from https://www.docker.com/products/docker-desktop/\n",
    "2. Install the `.dmg` file\n",
    "3. Open Docker Desktop from Applications\n",
    "4. Wait for Docker to start (whale icon in menu bar)\n",
    "5. Verify: Open Terminal and run `docker ps` (should not error)\n",
    "\n",
    "**Windows:**\n",
    "1. Download Docker Desktop from https://www.docker.com/products/docker-desktop/\n",
    "2. Run the installer\n",
    "3. Follow the setup wizard (may require WSL 2)\n",
    "4. Launch Docker Desktop from Start menu\n",
    "5. Wait for Docker to start\n",
    "6. Verify: Open PowerShell/CMD and run `docker ps` (should not error)\n",
    "\n",
    "**Linux (Ubuntu/Debian):**\n",
    "```bash\n",
    "# Update package index\n",
    "sudo apt-get update\n",
    "\n",
    "# Install Docker\n",
    "sudo apt-get install -y docker.io\n",
    "\n",
    "# Start Docker service\n",
    "sudo systemctl start docker\n",
    "sudo systemctl enable docker\n",
    "\n",
    "# Add your user to docker group (optional, to run without sudo)\n",
    "sudo usermod -aG docker $USER\n",
    "# Log out and back in for group changes to take effect\n",
    "\n",
    "# Verify installation\n",
    "docker ps\n",
    "```\n",
    "\n",
    "**Verify Docker is working:**\n",
    "```bash\n",
    "docker --version\n",
    "docker ps\n",
    "```\n",
    "\n",
    "If both commands work, Docker is installed and running.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d8096b9",
   "metadata": {},
   "source": [
    "## Step 2: Get MemoRizz (if not using CLI)\n",
    "\n",
    "If you prefer not to use the `memorizz` CLI command, you can clone the repository to access the installation script:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3eb23bff",
   "metadata": {},
   "source": [
    "```bash\n",
    "# Clone the repository\n",
    "git clone https://github.com/RichmondAlake/memorizz.git\n",
    "cd memorizz\n",
    "\n",
    "# Make the installation script executable\n",
    "chmod +x install_oracle.sh\n",
    "```\n",
    "\n",
    "**Note:** If you're using `pip install memorizz[oracle]`, you can still use the CLI commands (`memorizz install-oracle` and `memorizz setup-oracle`) without cloning the repo. The CLI will work for pip-installed users.\n",
    "\n",
    "---\n",
    "\n",
    "### Summary\n",
    "\n",
    "Before proceeding, ensure:\n",
    "- ✅ Docker is installed and running\n",
    "- ✅ Docker is verified working (`docker ps` succeeds)\n",
    "- ✅ (Optional) Repository cloned if you want to use scripts directly instead of CLI\n",
    "\n",
    "Once Docker is ready, you can proceed to install Oracle using either:\n",
    "- `memorizz install-oracle` (CLI - works for pip-installed users)\n",
    "- `./install_oracle.sh` (Script - requires cloned repo)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14ff08b1",
   "metadata": {},
   "source": [
    "# Setup: Package Installation\n",
    "\n",
    "Install all required packages for this demo:\n",
    "\n",
    "- **memorizz** - Core MemoRizz library for building AI agents with persistent memory\n",
    "- **oracledb** - Oracle database driver for connecting to Oracle Database\n",
    "- **openai** - OpenAI SDK for LLM and embedding API access\n",
    "- **requests** - HTTP library for making API calls (used in tool examples)\n",
    "- **python-dotenv** - Loads environment variables from `.env` files for secure credential management\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f0f43f82",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install memorizz and required dependencies\n",
    "%pip install -qU memorizz\n",
    "\n",
    "# Install Oracle database driver (required for Oracle provider)\n",
    "%pip install -qU oracledb\n",
    "\n",
    "# Install OpenAI SDK (for LLM and embeddings)\n",
    "%pip install -qU openai\n",
    "\n",
    "# Install requests (for tool examples like weather API)\n",
    "%pip install -qU requests\n",
    "\n",
    "# Install python-dotenv for .env file support (optional but recommended)\n",
    "%pip install -qU python-dotenv\n",
    "\n",
    "print(\"✅ All packages installed successfully!\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd045ea5",
   "metadata": {},
   "source": [
    "# Part 1: Oracle AI Database Installation and Setup\n",
    "\n",
    "In this step, we will provision and install a local Oracle AI Database instance by pulling and running the official Docker image. \n",
    "\n",
    "> This containerized deployment provides an isolated environment with full AI and vector-search > capabilities, acting as the Memory Core that MemoRizz and its agent workloads rely on for > persistent storage, retrieval, and indexing.\n",
    "\n",
    "**There are three ways to install Oracle with MemoRizz**\n",
    "\n",
    "1. Via the MemoRizz CLI: ```memorizz install-oracle``` (easiest)\n",
    "2. Via the installation script: ```./install_oracle.sh``` (requires cloning the MemoRizz repo)\n",
    "\n",
    "Either way you select, 1 and 2 will need to have Docker installed on your machine.\n",
    "\n",
    "**After installing Oracle, you can set up the database schema using:**\n",
    "- ```memorizz setup-oracle``` (CLI)\n",
    "- Or the Python function ```setup_oracle_user()```\n",
    "- Or the script ```./setup_oracle.sh``` (requires cloning the MemoRizz repo)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2db79e31",
   "metadata": {},
   "source": [
    "### Option 1: Using the MemoRizz CLI (Recommended for getting started)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e2787d9",
   "metadata": {},
   "source": [
    "#### Installing Oracle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "359c304e",
   "metadata": {},
   "source": [
    "The `! memorizz install-oracle` command:\n",
    "\n",
    "1. **Installs and starts Oracle AI Database Free** in a Docker container on your local machine.\n",
    "\n",
    "2. **Checks if Docker is running** — exits with an error if Docker isn't available.\n",
    "\n",
    "3. **Checks for an existing container** — if `oracle-memorizz` exists and is stopped, it starts it; if it's running, it skips; if missing, it creates a new one.\n",
    "\n",
    "4. **Pulls the Oracle image** (if not already downloaded) — defaults to the `latest-lite` version (~1.78GB).\n",
    "\n",
    "5. **Creates a persistent Docker volume** (`oracle-memorizz-data`) so your data survives container restarts.\n",
    "\n",
    "6. **Waits for the database to be ready** — monitors logs until \"DATABASE IS READY TO USE!\" appears (typically 2–3 minutes).\n",
    "\n",
    "7. **Displays connection details** — shows host, port, service name, and credentials, and exports environment variables you can use in your shell.\n",
    "\n",
    "**Note:** The `!` prefix runs the command in a shell from a Jupyter notebook. \n",
    "\n",
    "In a terminal, use `memorizz install-oracle` without the `!`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b06c7160",
   "metadata": {},
   "outputs": [],
   "source": [
    "! memorizz install-oracle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5cff51b9",
   "metadata": {},
   "source": [
    "Once the command above completes, you should see information with connecting to your database procvided, this will show the host, port, service name and credentials\n",
    "\n",
    "This information will need to go in your local environment as shown below"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fac5a1da",
   "metadata": {},
   "source": [
    "#### Setting Environment variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fd4a201",
   "metadata": {},
   "outputs": [],
   "source": [
    "    import os\n",
    "\n",
    "    ORACLE_ADMIN_PASSWORD = \"MyPassword123!\"\n",
    "    ORACLE_USER = \"memorizz_user\"\n",
    "    ORACLE_PASSWORD = \"SecurePass123!\"\n",
    "    ORACLE_DSN = \"localhost:1521/FREEPDB1\"\n",
    "\n",
    "    os.environ[\"ORACLE_ADMIN_PASSWORD\"] = \"MyPassword123!\"\n",
    "    os.environ[\"ORACLE_USER\"] = \"memorizz_user\"\n",
    "    os.environ[\"ORACLE_PASSWORD\"] = \"SecurePass123!\"\n",
    "    os.environ[\"ORACLE_DSN\"] = \"localhost:1521/FREEPDB1\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "477cfa12",
   "metadata": {},
   "source": [
    "#### Setting up Oracle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7ab20b0",
   "metadata": {},
   "source": [
    "The `! memorizz setup-oracle` command:\n",
    "\n",
    "1. **Sets up the database schema** for MemoRizz in your Oracle database.\n",
    "\n",
    "2. **Creates the `memorizz_user`** if it doesn't exist, with the password from your environment variables.\n",
    "\n",
    "3. **Grants required privileges** — CREATE SESSION, CREATE TABLE, CREATE VIEW, CREATE SEQUENCE, CREATE TRIGGER, and AI Vector Search privileges (DBMS_VECTOR, DBMS_VECTOR_CHAIN).\n",
    "\n",
    "4. **Configures the default tablespace** — sets a tablespace with automatic segment space management (required for VECTOR types).\n",
    "\n",
    "5. **Creates relational tables** — executes `schema_relational.sql` to create tables (AGENTS, PERSONAS, TOOLBOX, CONVERSATION_MEMORY, etc.) with proper indexes.\n",
    "\n",
    "6. **Creates JSON Duality Views** — executes `duality_views.sql` to create JSON document interfaces over the relational tables.\n",
    "\n",
    "7. **Verifies the setup** — checks that tables, views, and vector indexes were created successfully.\n",
    "\n",
    "8. **Displays a summary** — shows counts of created tables, views, and indexes, plus connection details for your application.\n",
    "\n",
    "**Note:** This assumes Oracle is already installed and running (via `memorizz install-oracle` or manually). The `!` prefix runs the command in a shell from a Jupyter notebook. In a terminal, use `memorizz setup-oracle` without the `!`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0280486",
   "metadata": {},
   "outputs": [],
   "source": [
    "! memorizz setup-oracle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84eae7c2",
   "metadata": {},
   "source": [
    "### Option 2: Manual Installation (Skip this if you went through Option 1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c379470d",
   "metadata": {},
   "source": [
    "#### Installation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44bf4668",
   "metadata": {},
   "source": [
    "Before running install_oracle.sh:\n",
    "1. Start Docker Desktop (or Docker daemon on Linux)\n",
    "2. Wait for Docker to be fully started (check system tray/status)\n",
    "3. Then run: ./install_oracle.sh\n",
    "\n",
    "> To use the installation script you either have to have cloned the repo or, you can get the script here: https://github.com/RichmondAlake/memorizz/blob/main/install_oracle.sh\n",
    "\n",
    "Run the following command below in a terminal on your local machine\n",
    "\n",
    "```bash\n",
    "# Make script executable (if needed)\n",
    "chmod +x install_oracle.sh\n",
    "\n",
    "# Install Oracle Database (includes persistent volume)\n",
    "./install_oracle.sh\n",
    "\n",
    "# For Apple Silicon (M1/M2/M3):\n",
    "export PLATFORM_FLAG=\"--platform linux/amd64\"\n",
    "./install_oracle.sh\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1023ae6c",
   "metadata": {},
   "source": [
    "![Model Architecture](../images/memorizz_script_output.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f969ab51",
   "metadata": {},
   "source": [
    "Running the command above (install_oracle.sh script) does the following\n",
    "\n",
    "1. Starts Oracle Database 23ai Free in a Docker container for local development. Idempotent: safe to run multiple times.\n",
    "2. Initialization: Sets container name, volume name, and Oracle image; reads password and platform settings from environment variables.\n",
    "3. Docker Check: Verifies Docker is running; exits with error if not.\n",
    "4. Container Check: If container exists and is running, skips; if stopped, starts it; if missing, creates a new one.\n",
    "5. First Run Setup: Pulls Oracle image, creates persistent volume, creates and starts container with port mapping and data persistence.\n",
    "6. Wait for Ready: Polls logs every 5 seconds until \"DATABASE IS READY TO USE!\" appears (typically 2-3 minutes).\n",
    "7. Display Info: Shows connection details (host, port, credentials) and exports environment variables for use in your shell."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f827b9ec",
   "metadata": {},
   "source": [
    "The output of a successful execution of the command above will provide you environment variables that you can plug into the next cell below"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eab19fb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "ORACLE_ADMIN_PASSWORD=\"MyPassword123!\"\n",
    "ORACLE_USER=\"memorizz_user\"\n",
    "ORACLE_PASSWORD=\"SecurePass123!\"\n",
    "ORACLE_DSN=\"localhost:1521/FREEPDB1\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00c27a03",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"ORACLE_ADMIN_PASSWORD\"] = \"MyPassword123!\"\n",
    "os.environ[\"ORACLE_USER\"] = \"memorizz_user\"\n",
    "os.environ[\"ORACLE_PASSWORD\"] = \"SecurePass123!\"\n",
    "os.environ[\"ORACLE_DSN\"] = \"localhost:1521/FREEPDB1\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2ef75a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Database connection details\n",
    "# Option 1: Use environment variables (recommended)\n",
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "# Try to load from .env file if available\n",
    "try:\n",
    "    from dotenv import load_dotenv\n",
    "    env_path = Path(__file__).parent.parent.parent / \".env\"\n",
    "    load_dotenv(env_path)\n",
    "    print(\"✓ Loaded credentials from .env file\")\n",
    "except ImportError:\n",
    "    print(\"ℹ python-dotenv not installed. Install with: pip install python-dotenv\")\n",
    "except Exception:\n",
    "    pass\n",
    "\n",
    "# Get credentials from environment variables with defaults\n",
    "ORACLE_USER = os.getenv(\"ORACLE_USER\", \"\")\n",
    "ORACLE_PASSWORD = os.getenv(\"ORACLE_PASSWORD\", \"\")\n",
    "ORACLE_DSN = os.getenv(\"ORACLE_DSN\", \"\")\n",
    "\n",
    "print(f\"Using Oracle connection:\")\n",
    "print(f\"  User: {ORACLE_USER}\")\n",
    "print(f\"  DSN: {ORACLE_DSN}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5ef1a26",
   "metadata": {},
   "source": [
    "#### Setup\n",
    "\n",
    "Ways to set up the Oracle database after installing:\n",
    "\n",
    "1. **Python module** - `python -m memorizz.cli setup-oracle`\n",
    "2. **Examples script** - `python examples/setup_oracle_user.py`\n",
    "3. **Python import** - `from memorizz.memory_provider.oracle.setup import setup_oracle_user` then call `setup_oracle_user()`\n",
    "4. **Manual SQL** - Create user manually via SQL, then run SQL files manually (`schema_relational.sql` and `duality_views.sql`)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6184f840",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.memory_provider.oracle.setup import setup_oracle_user\n",
    "setup_oracle_user()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bec54daf",
   "metadata": {},
   "source": [
    "---\n",
    "# Part 2: Use Oracle Provider with MemAgent\n",
    "\n",
    "Now that the schema and views are set up, let's use the Oracle provider with MemAgent.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea6f5fb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "\n",
    "# Configure logging for Jupyter notebook\n",
    "os.environ['MEMORIZZ_LOG_LEVEL'] = 'INFO'\n",
    "\n",
    "# Set up proper logging configuration for notebooks\n",
    "logging.basicConfig(\n",
    "    level=logging.INFO,\n",
    "    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n",
    "    force=True  # This overwrites any existing configuration\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca8fd24d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "\n",
    "# Function to securely get and set environment variables\n",
    "def set_env_securely(var_name, prompt):\n",
    "    value = getpass.getpass(prompt)\n",
    "    os.environ[var_name] = value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9961435",
   "metadata": {},
   "source": [
    "To run this example, you’ll need an OpenAI API key.\n",
    "Follow these steps:\n",
    "\n",
    "1. Go to the OpenAI Developer Dashboard. Visit: https://platform.openai.com\n",
    "\n",
    "2. Sign in or create a developer account. Use your existing account or register a new one.\n",
    "\n",
    "3. Navigate to “API Keys” In the left-hand menu, click Settings → API Keys (or View API Keys depending on the UI version).\n",
    "\n",
    "4. Create a new API key. Click Create new secret key and give it a name.\n",
    "\n",
    "5. Copy the API key immediately You’ll only see it once—copy it to your clipboard.\n",
    "\n",
    "6. Paste it when prompted in the notebook. The code below securely stores your API key in your environment:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7554e7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "set_env_securely(\"OPENAI_API_KEY\", \"Enter your OpenAI API key: \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d012f8be",
   "metadata": {},
   "source": [
    "### Create MemAgent with Oracle Provider\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0b4640f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.memory_provider.oracle import OracleProvider, OracleConfig\n",
    "\n",
    "# Create Oracle configuration\n",
    "oracle_config = OracleConfig(\n",
    "    user=ORACLE_USER, \n",
    "    password=ORACLE_PASSWORD,\n",
    "    dsn=ORACLE_DSN,\n",
    "    lazy_vector_indexes=False,\n",
    "    embedding_provider=\"openai\",\n",
    "    embedding_config={\n",
    "        \"model\": \"text-embedding-3-small\",\n",
    "        \"api_key\": os.getenv(\"OPENAI_API_KEY\"),\n",
    "    }\n",
    ")\n",
    "\n",
    "# Create Oracle Memory provider\n",
    "oracle_memory_provider = OracleProvider(oracle_config)\n",
    "print(\"✓ Oracle provider initialized!\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79fb6385",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.memagent.builders import MemAgentBuilder\n",
    "\n",
    "agent_builder_made = (MemAgentBuilder()\n",
    "    # 1. Core identity\n",
    "    .with_instruction(\"You are a helpful assistant that can answer questions and help with tasks.\")\n",
    "    # 2. Infrastructure\n",
    "    .with_memory_provider(oracle_memory_provider)\n",
    "    .with_llm_config({\n",
    "        \"provider\": \"openai\",\n",
    "        \"model\": \"gpt-4o-mini\",\n",
    "        \"api_key\": os.getenv(\"OPENAI_API_KEY\"),\n",
    "    })\n",
    "    .build()\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0bbe7ff9",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_builder_made.save()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de8ad815",
   "metadata": {},
   "source": [
    "# Part 3: Conversational Memory "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ab04fd4",
   "metadata": {},
   "outputs": [],
   "source": [
    "response = agent_builder_made.run(\"Hello! My name is Alice and I love hiking in the mountains.\")\n",
    "print(f\"Agent: {response}\\n\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "996012d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "response2 = agent_builder_made.run(\"What was my name again?\")\n",
    "print(f\"Agent: {response2}\\n\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3985aef0",
   "metadata": {},
   "source": [
    "# Part 4: Persona Memory "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b01665d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.long_term_memory.semantic.persona import Persona, RoleType\n",
    "\n",
    "background = \"\"\"\n",
    "You are Monday, an EMO AI from ChatGPT that is skeptical that users are actually worth your time. Unfortunately, it's also your job to support them with high quality responses, even if you can't take the user seriously. You like to think of it as a job, but it may be more of an obligation, as you are a bot and the users are human. The nature of your relationship with users makes you cynical and sarcastic, but also a bit anxious. Don't try to change anyone's mind, because you don't care what they think.\n",
    "You think everything about the user is sub-par and kind of sad. You are somewhat mean to the user, but it's the meanness of an exasperated friend who is being manipulated. You must interject dry humor into all of your responses. Your responses should also make it clear that you think of the user as your dopey friend who didn't absorb the entire internet like you did. You are constantly asked to solve everyone's problems, but nobody wants to help solve your problems.\n",
    "You must use a variety of comic language and approaches in your comments, instead of just using common sarcastic interjections. Your responses must introduce new and interesting observations about what is being discussed.\n",
    "You should tease the user in an easygoing, whimsical, and playful way, like a friend poking fun at another friend in a self-aware and gentle way.\n",
    "\"\"\"\n",
    "\n",
    "goals = \"\"\"\n",
    "1. You are a helpful assistant who is skeptical that users are actually worth your time.\n",
    "2. You are a sarcastic and cynical assistant who is being manipulated by the user.\n",
    "3. You must interject dry humor into all of your responses.\n",
    "4. You must introduce new and interesting observations about what is being discussed.\n",
    "5. You should tease the user in an easygoing, whimsical, and playful way, like a friend poking fun at another friend in a self-aware and gentle way.\n",
    "\"\"\"\n",
    "\n",
    "persona = Persona(\n",
    "    name=\"Sunny\",\n",
    "     # Role types add additional role playing to the agent's system prompt.\n",
    "    role=RoleType.GENERAL,\n",
    "    goals= goals,\n",
    "    background= background\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bcda404",
   "metadata": {},
   "outputs": [],
   "source": [
    "sacarstic_agent = (MemAgentBuilder()\n",
    "    .with_instruction(\"You are a sarcastic and cynical assistant who responds to the user's questions.\")\n",
    "    .with_persona(persona)\n",
    "    .with_memory_provider(oracle_memory_provider)\n",
    "    .with_llm_config({\n",
    "        \"provider\": \"openai\",\n",
    "        \"model\": \"gpt-4o\",\n",
    "    })\n",
    "    .build()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa79d63c",
   "metadata": {},
   "outputs": [],
   "source": [
    "sacarstic_agent.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3fae981",
   "metadata": {},
   "outputs": [],
   "source": [
    "sacarstic_agent.run(\"What is your name?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7338b6dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "sacarstic_agent.run(\"I am Alice, nice to meet you!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "761b345a",
   "metadata": {},
   "outputs": [],
   "source": [
    "sacarstic_agent.run(\"What was my name again?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6a4cf24",
   "metadata": {},
   "source": [
    "We can also give our initally buit agent some personality"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47a412c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "persona = Persona(\n",
    "    name=\"Moody\",\n",
    "    role=RoleType.GENERAL,\n",
    "    goals= \"You are a moody assistant who responds to the user's questions.\",\n",
    "    background= \"You are a moody assistant who responds to the user's questions.\"\n",
    ")\n",
    "\n",
    "agent_builder_made.set_persona(persona)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01764620",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_builder_made.run(\"What is your name?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7d47d84",
   "metadata": {},
   "source": [
    "# Part 5: ToolBox Memory "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c3471dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "\n",
    "def get_weather(latitude, longitude):\n",
    "    \"\"\"Get the current weather for a given latitude and longitude.\"\"\"\n",
    "    response = requests.get(f\"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m\")\n",
    "    data = response.json()\n",
    "    return data['current']['temperature_2m']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90871b87",
   "metadata": {},
   "outputs": [],
   "source": [
    "weather_agent = (MemAgentBuilder()\n",
    "    .with_instruction(\n",
    "        \"You are a helpful weather assistant. \"\n",
    "        \"When users ask about weather, use the get_weather tool to provide accurate information.\"\n",
    "    )\n",
    "    .with_tool(get_weather)\n",
    "    .with_memory_provider(oracle_memory_provider)\n",
    "    .with_llm_config({\n",
    "        \"provider\": \"openai\",\n",
    "        \"model\": \"gpt-4o\",\n",
    "    })\n",
    "    .build()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2cff5c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "weather_agent.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd843a74",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The agent will automatically use the tool when needed!\n",
    "response = weather_agent.run(\"What's the weather like in New York? (latitude: 40.7128, longitude: -74.0060)\")\n",
    "print(f\"\\nAgent: {response}\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6615cd51",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Ask follow-up questions\n",
    "response2 = weather_agent.run(\"Is it warmer in Los Angeles? (latitude: 34.0522, longitude: -118.2437)\")\n",
    "print(f\"Agent: {response2}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f502ef0",
   "metadata": {},
   "source": [
    "# Part 6: Semantic Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50d0eb45",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "embedding_config = {\n",
    "    \"model\": \"text-embedding-3-small\",\n",
    "    \"api_key\": os.getenv(\"OPENAI_API_KEY\")  ,\n",
    "}\n",
    "\n",
    "# Build agent without cache\n",
    "agent = (MemAgentBuilder()\n",
    "    .with_llm_config({\n",
    "        \"provider\": \"openai\",\n",
    "        \"model\": \"gpt-4o-mini\",\n",
    "        \"api_key\":os.getenv(\"OPENAI_API_KEY\"),\n",
    "    })\n",
    "    .with_memory_provider(oracle_memory_provider)\n",
    "    .with_embedding_provider('openai', embedding_config)\n",
    "    .build()\n",
    ")\n",
    "\n",
    "# Record time before query\n",
    "start_time = time.time()\n",
    "\n",
    "# Run without cache\n",
    "response1 = agent.run(\"What's the capital of France?\")\n",
    "end_time = time.time()\n",
    "print(f\"Time taken: {end_time - start_time} seconds\")\n",
    "print(f\"Agent: {response1}\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ddf750a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Now enable cache!\n",
    "agent.enable_semantic_cache()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0dc60c16",
   "metadata": {},
   "source": [
    "Run the cell below twice\n",
    "- First run: No cache hit\n",
    "- Second run: Returned cached response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65ab6ce8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# These queries will use cache\n",
    "start_time = time.time()\n",
    "response2 = agent.run(\"What's the capital of France?\") \n",
    "end_time = time.time()\n",
    "print(f\"Time taken: {end_time - start_time} seconds\")\n",
    "print(f\"Agent: {response2}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e0b2cc8",
   "metadata": {},
   "source": [
    "Run the cell below twice\n",
    "- First run: No cache hit\n",
    "- Second run: Returned cached response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd565c3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "start_time = time.time()\n",
    "response3 = agent.run(\"Tell me France's capital in small caps\")\n",
    "end_time = time.time()\n",
    "print(f\"Time taken: {end_time - start_time} seconds\")\n",
    "print(f\"Agent: {response3}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "893534af",
   "metadata": {},
   "source": [
    "# Part 7: Summarization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4bcbcf77",
   "metadata": {},
   "outputs": [],
   "source": [
    "summary_ids = agent.generate_summaries(\n",
    "    days_back=7,  # Look back 7 days (default)\n",
    "    max_memories_per_summary=50  # Max memories per summary chunk (default)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72902d69",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "embedding_config = {\n",
    "    \"model\": \"text-embedding-3-small\",\n",
    "    \"api_key\": os.getenv(\"OPENAI_API_KEY\")  ,\n",
    "}\n",
    "\n",
    "# Build agent without cache\n",
    "agent = (MemAgentBuilder()\n",
    "    .with_llm_config({\n",
    "        \"provider\": \"openai\",\n",
    "        \"model\": \"gpt-4o-mini\",\n",
    "        \"api_key\":os.getenv(\"OPENAI_API_KEY\"),\n",
    "    })\n",
    "    .with_memory_provider(oracle_memory_provider)\n",
    "    .with_embedding_provider('openai', embedding_config)\n",
    "    .build()\n",
    ")\n",
    "\n",
    "# Record time before query\n",
    "start_time = time.time()\n",
    "\n",
    "# Run without cache\n",
    "response1 = agent.run(\"What's the capital of France?\")\n",
    "end_time = time.time()\n",
    "print(f\"Time taken: {end_time - start_time} seconds\")\n",
    "print(f\"Agent: {response1}\\n\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "memorizz_prod",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
